const URL = "https://xcx.dbywuliuyunshugl.com/YDYA/";
const API_URL = "https://xcx.dbywuliuyunshugl.com/YDYA/";
const IMAGEURL = "https://xcx.dbywuliuyunshugl.com/YDYA/";


import {
    setSign
} from './encrypt';


let cLoading = true;
const gTo = function(url) {
    uni.navigateTo({
        url: url,
        animationType: 'pop-in',
        animationDuration: 200
    });
}
const cTo = function(url) {
    uni.redirectTo({
        url: url
    });
}
const sTo = function(url) {
    uni.switchTab({
        url: url
    });
}

const backT = function() {
    uni.navigateBack();
}


// input失去焦点
const inputBlur = () => {
    uni.pageScrollTo({
        scrollTop: 0,
        duration: 0
    });
}


const _upLoadVideo = function(e) {
    return new Promise((resolve, reject) => {
        uni.uploadFile({
            url: URL + 'file/upload_file',
            filePath: e,
            name: 'file',
            formData: {
                'id': ''
            },
            success: (res) => {
                let item = JSON.parse(res.data.replace(/\ufeff/g, ""));
                resolve(item)
            }
        });
    })
}

const getSync = (i) => {
    return uni.getStorageSync(i);
}
const removeSync = (i) => {
    return uni.removeStorageSync(i);
}
const setSync = (i, data) => {
    return uni.setStorageSync(i, data);
}
const isNull = (data) => {
    let dataType = typeof(data); //typeof 返回的是字符串，有六种可能：”number”、”string”、”boolean”、”object”、”function”、”undefined”;
    switch (dataType) {
        case "number": //数字
            return false;
            break;
        case "string": //字符串
            if (data == '') { //为空
                return true;
            } else {
                return false;
            }
            break;
        case "boolean": //布尔值
            return data;
            break;
        case "object": //对象
            if (!data && typeof(data) != "undefined" && data != 0) { //为null
                return true;
            } else {
                for (var key in data) { //非空对象
                    return false;
                }
                return true;
            }
            break;
        case "function": //函数
            return false;
            break;
        case "undefined": //undefined
            return true;
            break;
    }
};
const _alert = (txt, cb) => {
    uni.showModal({
        title: '温馨提示',
        content: txt,
        showCancel: false,
        confirmColor: '#ff5e26',
        success: function() {
            cb && cb();
        }
    });
}

const setHeight = function() {
    uni.getSystemInfo({
        success: function(res) {
            uni.setStorage({
                key: 'MHeight',
                data: {
                    'tHeight': uni.getSystemInfoSync().statusBarHeight,
                    'rHeight': 44,
                    'fHeight': res.screenHeight - res.windowHeight - 48
                }
            });
        }
    });
}
const _upLoadPic = function(e) {
    return new Promise((resolve, reject) => {
        uni.uploadFile({
            url: URL + 'api/' + 'upload_image',
            filePath: e,
            name: 'image',
            // formData: {
            //     type: 'image',
            //     path: 'upload',
            //     module: 'api'
            // },
            success: (res) => {
                let item = JSON.parse(res.data.replace(/\ufeff/g, ""));
                resolve(item)
            }
        });
    })
}
const _confirm = function(txt, cb) {
    uni.showModal({
        title: '温馨提示',
        content: txt,
        showCancel: true,
        confirmColor: '#ff5e26',
        success: function(res) {
            if (res.confirm) {
                cb && cb();
            }
        }
    });
}

const getParam = () => {
    var url = encodeURI(encodeURI(location.search)); //获取url中"?"符后的字串
    var theRequest = new Object();
    if (url.indexOf("?") !== -1) {
        var str = url.substr(1);
        var strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = decodeURI(decodeURI(unescape(strs[i].split("=")[1])));
        }
    }
    return theRequest;
}

const _toast = function(txt) {
    uni.showToast({
        title: txt,
        duration: 1500,
        icon: 'none',
        mask: true,
    });
}

const toDs = function(dates, type) {
    let date = new Date(dates * 1000);
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var h = date.getHours();
    var i = date.getMinutes();
    var s = date.getSeconds();
    if (h < 10) {
        h = '0' + h;
    }
    if (i < 10) {
        i = '0' + i;
    }
    if (s < 10) {
        s = '0' + s;
    }
    return year + '-' + month + '-' + day;
}


// 节流函数

const throttle = (fn, gapTime) => {
    if (gapTime == null || gapTime == undefined) {
        gapTime = 1500
    }
    let _lastTime = 1000
    return new Promise((fn, reject) => {
        // console.log(Number(_nowTime) - Number(_lastTime))
        if (_nowTime - _lastTime > gapTime || !_lastTime) {
            // console.log(8888)
            fn();
            _lastTime = _nowTime
        }
    })
}


const ajaxPost = function(urls, datas, types, status) {
    if (!urls) {
        return;
    }
    if (cLoading) {
        cLoading = false;
        if (!status) {
            // uni.showLoading({
            //     title: '加载中',
            //     mask: true
            // });
        }
    }
    return new Promise((resolve, reject) => {
        uni.request({
            url: URL + 'api/' + urls,
            method: types || "POST",
            data: datas,
            header: {
                signature: setSign()
            },
            success: (res) => {
                if (res.data.success == 1000) {
                    resolve(res.data);
                    uni.hideLoading();
                    cLoading = true;
                } else if (res.data.success == 1) {
                    if (urls == 'modify_positioning') {
                        uni.hideLoading();
                    } else {
                        uni.hideLoading();
                        uni.showToast({
                            title: res.data.message,
                            icon: 'none',
                            duration: 2000
                        });
                    }
                    resolve(res.data);
                    // cLoading = true;
                } else if (res.data.success == 444) {
                    // 444禁用  离职
                    //小程序未登录或者过期
                    uni.$emit('logOut')
                    resolve(res.data);
                    uni.hideLoading();
                    uni.showToast({
                        title: '该账号被禁用或已离职！',
                        icon: 'none',
                        duration: 2000
                    });
                    uni.removeStorageSync('userToken')
                    uni.removeStorageSync('userId')
                    uni.removeStorageSync('userInfo')
					uni.removeStorageSync('identity')
					uni.removeStorageSync('MOBILE')
                    

                    // #ifdef MP-WEIXIN
                    // 跳转微信授权
                    uni.navigateTo({
                        url: "/pagesA/login/login"
                    })
                    // #endif
                    // #ifdef APP-PLUS
                    // 跳转app登录
                    uni.navigateTo({
                        url: "/pagesA/login/login"
                    })
                    // #endif
                } else if (res.data.success == 1004) {
                    //小程序未登录或者过期
                    resolve(res.data);
                    uni.$emit('logOut')
                    uni.hideLoading();
                    uni.showToast({
                        title: '该账号异地登录，请重新登录！',
                        icon: 'none',
                        duration: 2000
                    });
                    uni.removeStorageSync('userToken')
                    uni.removeStorageSync('userId')
                    uni.removeStorageSync('userInfo')
					uni.removeStorageSync('identity')
					uni.removeStorageSync('MOBILE')
                    
                    // #ifdef MP-WEIXIN
                    // 跳转微信授权
                    uni.navigateTo({
                        url: "/pagesA/login/login"
                    })
                    // #endif
                    // #ifdef APP-PLUS
                    // 跳转app登录
                    uni.navigateTo({
                        url: "/pagesA/login/login"
                    })
                    // #endif
                } else if (res.data.success == -777) {
                    //用户禁用
                    resolve(res.data);
                    uni.hideLoading();
                    uni.$emit('logOut')
                    uni.removeStorageSync('userToken')
                    uni.removeStorageSync('userId')
                    uni.removeStorageSync('userInfo')
					uni.removeStorageSync('identity')
					uni.removeStorageSync('MOBILE')
                    
                    uni.navigateTo({
                        url: "/pages/tabbar/index"
                    })
                } else {
                    if (urls == 'modify_positioning') {
                        uni.hideLoading();
                    } else {
                        uni.hideLoading();
                        _toast(res.data.message);
                    }
                }
            },
            fail: (res) => {
                if (urls == 'modify_positioning') {
                    uni.hideLoading();
                    cLoading = true;
                } else {
                    reject(res)
                    uni.hideLoading();
                    cLoading = true;
                }
            },
            complete(ret) {
                // console.log(datas)
                console.log(urls,datas)
                console.log(urls,ret)
            }
        });
    })
}



/**
 * 加载loading
 * @param msg
 */
export const showLoading = (msg = '') => uni.showLoading({
    mask: true,
    title: msg
});

/**
 * 关闭loading
 */
export const closeLoading = () => uni.hideLoading();

const getTokens = function() {
    let value = uni.getStorageSync('token');
    if (value && value.length > 0) {
        return value;
    } else {
        // console.log('获取失败')
        return false;
    }
}
const getHeight = function() {
    return uni.getStorageSync('MHeight');
}

const _call = function(tel) {
    // #ifdef APP-PLUS
    var galleryPermission = plus.navigator.checkPermission("CALL_PHONE");
    if (galleryPermission == "undetermined") {
        _toast('电话权限使用说明：用于拨打电话');
    }
    // #endif
    uni.makePhoneCall({
        phoneNumber: tel
    });
}
const checkPhone = function(phoneNumber) {
    var phoneReg = /^1[3456789]\d{9}$/;
    if (phoneNumber == null || phoneNumber == "") {
        return false;
    } else if (!phoneReg.test(phoneNumber)) {
        return false;
    }
    return true;
}

// 验证身份证号
const testIdCard = function(idCard) {
    return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(idCard)
}

const replaceDetail = function(htmls) {
    return htmls.replace(/<img/g,
        '<img style="width:100% !important;height:auto;margin: 0 auto;padding: 0;vertical-align: top;display:block" '
    );
}
const wxConfig = ((url) => {
    let _this = this;
    ajaxPost('wx_config', {
        url: url.split('#')[0],
    }).then(res => {
        if (res.status == 0) {
            _this.$wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: res.data.appId, // 必填，公众号的唯一标识
                timestamp: res.data.timestamp, // 必填，生成签名的时间戳
                nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
                signature: res.data.signature, // 必填，签名
                jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'chooseImage',
                    'uploadImage', 'chooseWXPay'
                ], // 必填，需要使用的JS接口列表
            });
        } else {
            _toast(res.message)
        }
    })
})
//完成浏览任务
const browseFinish = function(url, callback) {
    ajaxPost('complete', {
        userToken: uni.getStorageSync('userToken'),
        parent_id: uni.getStorageSync('taskId'),
    }).then(res => {
        if (res.status == 0) {
            callback(res);
        } else {
            _toast(res.message)
        }
    })
}

const screenshot = (fromWhere, widthProp, proportion) => {
    var width = 0,
        height = 0;
    uni.getSystemInfo({
        //整个手机屏幕的高
        success: function(res) {
            console.log(res)
            width = parseInt(res.screenWidth * widthProp) //宽等于屏幕款*百分比
            height = width * proportion
        }
    });
    gTo('/pages/u-avatar-cropper/u-avatar-cropper?destWidth=' + (width * 2) + '&destHeight=' + (height * 2) +
        '&rectWidth=' + width + '&rectHeight=' + height + '&fileType=jpg' + '&fromWhere=' + fromWhere)
}
// 防止处理多次点击
const noMultipleClicks = function noMultipleClicks(methods, info) {
    // methods是需要点击后需要执行的函数， info是点击需要传的参数
    let that = this;
    if (that.noClick) {
        // 第一次点击
        that.noClick = false;
        if (info && info !== '') {
            // info是执行函数需要传的参数
            methods(info);
        } else {
            methods();
        }
        setTimeout(() => {
            that.noClick = true;
        }, 2000)
    } else {
        // 这里是重复点击的判断
    }
}

const _pay = function(order_no, callback) {
    var that = this;
    that.$ajax('repay', {
        userToken: that.$getSync('userToken'),
        id: order_no,
    }).then(ret => {
        if (ret.status == 0) {
            //发起支付
            uni.requestPayment({
                'timeStamp': ret.data.wxpay.timeStamp,
                'nonceStr': ret.data.wxpay.nonceStr,
                'package': ret.data.wxpay.package,
                'signType': 'MD5', //SHA256  RSA
                'paySign': ret.data.wxpay.paySign,
                success: function(sus) {
                    //执行支付成功提示
                    console.log(sus)
                    uni.navigateBack({
                        delta: 2
                    })
                },
                fail: function(err) {
                    console.log(err)
                }
            })
        } else {
            that.$toast(ret.message)
        }
    })
}

// 定位
const _getLocation = (cb) => {
    uni.getLocation({
        type: 'gcj02', //返回可以用于wx.openLocation的经纬度
        success(res) {
            console.log(res)
            let {
                latitude,
                longitude
            } = res;
            cb && cb(latitude, longitude);
            // cb && cb(qqMapTransBMap(longitude, latitude));
        },
        fail(err) {
            console.log(err)
            // #ifdef APP-PLUS
            _toast('检测到您没打开定位权限，请前往系统设置内开启');
            // #endif
            
            // #ifdef MP-WEIXIN
            uni.showModal({
                title: '温馨提示',
                content: '检测到您没打开定位权限，是否去设置打开？',
                success: function (res) {
                    if (res.confirm) {
                        wx.openSetting()
                    }
                }
            })
            // #endif
        }
    })
};

// 预览多张图片
const previewImage = function(list,index) {
    let urlImage = []
    console.log(list,index)
    list.forEach(item=>{
        if(item.image){
            urlImage.push(item.image)
        }else if(item){
            urlImage.push(item)
        }
    })
    uni.previewImage({
        urls: urlImage,
        current: index
    })
}

// 预览一张图片
const previewImageSA = function(item) {
    console.log(item)
    let urlImage = []
    urlImage[0] = item
    uni.previewImage({
        urls: urlImage,
        current: 0
    })
}

//删除照片
const _delImage = function(urlArr, urlArrId, index) {
    console.log(urlArr, urlArrId, index)
    uni.showModal({
        title: '温馨提示',
        content: '确定要删除照片吗？',
        success: res => {
            if (res.confirm) {
                urlArr.splice(index, 1);
                urlArrId.splice(index, 1);
            } else if (res.cancel) {
                
            }
        }
    });
}

export {
	previewImage,
	previewImageSA,
	_delImage,
    noMultipleClicks,
    URL,
    ajaxPost,
    getTokens,
    toDs,
    gTo,
    cTo,
    _toast,
    setHeight,
    getHeight,
    backT,
    _call,
    checkPhone,
    _confirm,
    isNull,
    _upLoadPic,
    _alert,
    replaceDetail,
    getSync,
    setSync,
    _upLoadVideo,
    removeSync,
    getParam,
    inputBlur,
    browseFinish,
    throttle,
    API_URL,
    IMAGEURL,
    screenshot,
    sTo,
    _pay,
    _getLocation,
    testIdCard
};
